from app.config import config
from muffin import Application
from muffin_databases import Plugin as DB

# 创建 app
app = Application(
    static_url_prefix=config['static'],
    static_folders=['static'],
    debug=config['debug']
)

config['db_args'] = dict(
    host=config['database']['host'],
    port=config['database']['port'],
    user=config['database']['user'],
    password=config['database']['pass'],
    database=config['database']['db'],
    charset=config['database']['chartset'],
)

# 数据库连接
config['db_url'] = "mysql://{user}:{password}@{host}:{port}/{database}?charset={charset}".format(**config['db_args'])

db = DB(url=config['db_url'])
db.setup(app)

# serializer
from functools import wraps
from inspect import isawaitable

def serializer(func):
    def decorator(f):
        @wraps(f)
        async def decorated_function(*args, **kwargs):
            retval = f(*args, **kwargs)
            if isawaitable(retval):
                retval = await retval
            return func(retval)

        return decorated_function

    return decorator